package hn.cch.spring_boot_redis.controller;

import hn.cch.spring_boot_redis.message.RedisRequest;
import hn.cch.spring_boot_redis.message.RedisResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@RequestMapping(value = "redis")
@Controller
public class RedisController {

    public static Logger logger = LoggerFactory.getLogger(RedisController.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping(value = "get")
    @ResponseBody
    public RedisResponse get(@RequestBody RedisRequest redisRequest) {
        logger.info("get");
        RedisResponse redisResponse = RedisResponse.success();
        Object value = redisTemplate.opsForValue().get(redisRequest.getKey());
        redisResponse.setKey(redisRequest.getKey());
        redisResponse.setValue(value.toString());
        return redisResponse;
    }


    @PostMapping(value = "set")
    @ResponseBody
    public RedisResponse set(@RequestBody RedisRequest redisRequest) {
        logger.info("set");
        RedisResponse redisResponse = RedisResponse.success();
        redisTemplate.opsForValue().set(redisRequest.getKey(), redisRequest.getValue());
        redisResponse.setKey(redisRequest.getKey());
        redisResponse.setValue(redisRequest.getValue());
        return redisResponse;
    }

}
